<?php
namespace app\merchant\controller;

use tp5_lib\common\controller\BaseController;
use think\facade\Session;
use app\merchant\model\MerchantModel;

class AuthController extends BaseController
{
    public function checkLogin()
    {
        if(!$user=Session::get("user")){
            $this->error("用户未登录",url("merchant/login/login"));
        }
        return $user;
    }
    /**
     * 提交资料页面
     */
    public function index()
    {
        $user=$this->checkLogin();
        $model=new MerchantModel();
        if($info=$model->db()->where(["user_id"=>$user["id"]])->find()){
            session("merchant_info",$info->toArray());
            if($info["status"] == "0"){
                $this->redirect("auth/wait");
            }
            elseif($info["status"] == "1"){
                $this->redirect("user/index/index");
            }
        }
        return $this->fetch();
    }
    /**
     * 提交资料
     */
    public function submit()
    {
        $user=$this->checkLogin();
        $data=input();
        $data["user_id"]=$user["id"];
        $data["time"]=time();

        $file = $this->request->file('license');
        $info = $file->move( env("root_path").'/public/uploads');
        if($info){
            $data["license"]=$info->getSaveName();
        }
        else{
            $this->error($file->getError());
        }

        $file = $this->request->file('idcard');
        $info = $file->move( env("root_path").'/public/uploads');
        if($info){
            $data["idcard"]=$info->getSaveName();
        }
        else{
            $this->error($file->getError());
        }

        $model=new MerchantModel();
        if(!$model->db()->insert($data)){
            $this->error("保存失败");
        }
        $this->success("提交成功");
    }
    /**
     * 等待审核
     */
    public function wait()
    {
        $user=$this->checkLogin();
        if(!$info=session("merchant_info")){
            $model=new MerchantModel();
            if($info=$model->db()->where(["user_id"=>$user["id"]])->find()){
                session("merchant_info",$info->toArray());
            }
            else{
                $this->redirect("index");
            }
        }
        $this->assign("info",$info);
        return $this->fetch();
    }
    /**
     * 审核未通过
     */
    public function failed()
    {
        $user=$this->checkLogin();
        if(!$info=session("merchant_info")){
            $model=new MerchantModel();
            if($info=$model->db()->where(["user_id"=>$user["id"]])->find()){
                session("merchant_info",$info->toArray());
            }
            else{
                $this->redirect("index");
            }
        }
        $this->assign("info",$info);
        return $this->fetch();
    }
}
